// 最长递增子序列
package Leetcode;


class Solution300_1 {
    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            int max = 0;
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i] && dp[j] > max)
                    max = dp[j];
            }
            dp[i] = max + 1;
        }
        int max = 0;
        for (int i = 0; i < nums.length; i++)
            if (dp[i] > max)
                max = dp[i];
        return max;
    }
}

class Solution300_2 {
    public int lengthOfLIS(int[] nums) {
        // dp[i]表示长度为i的最长上升子序列的末尾元素的最小值
        int len = 1;
        int[] d = new int[nums.length + 1];
        d[len] = nums[0];
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > d[len]) {
                len++;
                d[len] = nums[i];
            } else {
                int l = 1, r = len, pos = 0; // 如果找不到说明所有的数都比 nums[i] 大，此时要更新 d[1]，所以这里将 pos 设为 0
                while (l <= r) {
                    int mid = (l + r) >> 1;
                    if (d[mid] < nums[i]) {
                        pos = mid;
                        l = mid + 1;
                    } else {
                        r = mid - 1;
                    }
                }
                d[pos + 1] = nums[i];
            }
        }
        return len;
    }
}
